﻿namespace Microsoft.SharePoint.Client
{
    using System;
    using System.Collections;
    using System.Collections.Generic;

    internal class ClientQueryableResult<T> : IFromJson, IEnumerable<T>, IEnumerable where T: ClientObject
    {
        private List<T> m_data;

        public IEnumerator<T> GetEnumerator()
        {
            if (this.m_data == null)
            {
                throw new ClientRequestException(Resources.GetString("QueryableResultNotAvailable"));
            }
            return this.m_data.GetEnumerator();
        }

        bool IFromJson.CustomFromJson(JsonReader reader)
        {
            return false;
        }

        void IFromJson.FromJson(JsonReader reader)
        {
            if (reader == null)
            {
                throw new ArgumentNullException("reader");
            }
            this.m_data = new List<T>();
            if (reader.PeekTokenType() == JsonTokenType.Null)
            {
                reader.ReadObject();
            }
            else if (reader.PeekTokenType() == JsonTokenType.ArrayStart)
            {
                object[] objArray = reader.ReadObjectArray();
                for (int i = 0; i < objArray.Length; i++)
                {
                    this.m_data.Add(objArray[i] as T);
                }
            }
            else
            {
                reader.ReadObjectStart();
                bool flag = false;
                while (reader.PeekTokenType() != JsonTokenType.ObjectEnd)
                {
                    if (reader.PeekName() == "_Child_Items_")
                    {
                        reader.ReadName();
                        object[] objArray2 = reader.ReadObjectArray();
                        if (!flag)
                        {
                            for (int j = 0; j < objArray2.Length; j++)
                            {
                                this.m_data.Add(objArray2[j] as T);
                            }
                            flag = true;
                        }
                    }
                    else
                    {
                        reader.ReadName();
                        reader.ReadObject();
                    }
                }
                reader.ReadObjectEnd();
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }
    }
}

